#! /usr/bin/env python3
import cgi
import json
import hashlib


def get_config(path="config.json"):
    with open(path, "r+", encoding="utf-8") as f:
        json_dict = json.load(f)
        return json_dict


def get_main_html(head, body):
    header = head
    with open("html/main.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        constent = constent.format(main=body, sel_part="")
        return str(header + constent)


def get_input_html():
    input_str = "<div id=\"seach_input\"><form action=\"loginWeb.py\" method=\"get\">\n\
用户名：&nbsp;&nbsp;&nbsp;&nbsp;<input id=\"seach_input_text\" type=\"text\" name=\"user\"> <br />\n\
密&nbsp;&nbsp;&nbsp;&nbsp;码：&nbsp;&nbsp;&nbsp;&nbsp;<input id=\"seach_input_text\" type=\"password\" name=\"passwd\"> <br />\n\
<input id=\"seach_input_submit\" type=\"submit\" value=\"登陆\" />\n\
</form><br />\
<p><b>公告：</b>MD笔记系统为私人使用，不开放注册。如果是本人的朋友请看联系方式，发我邮件单独向我索要，并注明身份，谢谢。</p></div>"
    return str(input_str)


def main(note_path, except_list):
    head = "Content-type:text/html\n\n"
    html = get_main_html(head=head, body=get_input_html())
    print(html)


if __name__ == "__main__":
    head = "Content-type:text/html\n"
    config = get_config()
    pass_list = config.get("passwd", None)
    cgi_mod = cgi.FieldStorage()
    user = cgi_mod.getvalue('user', "None")
    passwd = cgi_mod.getvalue('passwd', "None")
    if user in ["", "None", "none"]:
        head += "Set-Cookie: state=\"None\"\n"
        head += "\n"
        last = get_main_html(head, "<meta http-equiv=\"refresh\" content=\"3;url=\\\"  /><div>3秒后登出...</div>")
    else:
        md5_strs = hashlib.md5((user + passwd).encode("utf-8")).hexdigest()
        if md5_strs in pass_list:
            head += "Set-Cookie: state=\"%s\"\n" % md5_strs
        head += "\n"
        last = get_main_html(head, "<meta http-equiv=\"refresh\" content=\"3;url=\\\"  /><div>3秒后自动跳转...</div>")
    print(last)
